package com.wht.sip.core.transmit.message;

import com.wht.sip.core.transmit.SIPSender;
import com.wht.sip.utils.SipUtils;
import gov.nist.javax.sip.message.SIPRequest;
import gov.nist.javax.sip.message.SIPResponse;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Managed;

import javax.sip.InvalidArgumentException;
import javax.sip.PeerUnavailableException;
import javax.sip.SipException;
import javax.sip.SipFactory;
import javax.sip.header.HeaderFactory;
import javax.sip.message.MessageFactory;
import javax.sip.message.Request;
import java.text.ParseException;

/**
 * @author by HaiTao.Wang on 2025/9/15.
 */
@Slf4j
@Managed
public class SipRequestProcessorHandle {

    @Inject
    private SIPSender sipSender;

    public HeaderFactory getHeaderFactory() {
        try {
            return SipFactory.getInstance().createHeaderFactory();
        } catch (PeerUnavailableException e) {
            log.error("未处理的异常 ", e);
        }
        return null;
    }

    public MessageFactory getMessageFactory() {
        try {
            return SipFactory.getInstance().createMessageFactory();
        } catch (PeerUnavailableException e) {
            log.error("未处理的异常 ", e);
        }
        return null;
    }


    /***
     * 回复状态码
     * 100 trying
     * 200 OK
     * 400
     * 404
     */
    public SIPResponse response(SIPRequest sipRequest, int statusCode) throws SipException, InvalidArgumentException, ParseException {
        return response(sipRequest, statusCode, null);
    }

    public SIPResponse response(SIPRequest sipRequest, int statusCode, String msg) throws SipException, InvalidArgumentException, ParseException {

        if (sipRequest.getToHeader().getTag() == null) {
            sipRequest.getToHeader().setTag(SipUtils.getNewTag());
        }
        SIPResponse response = (SIPResponse) getMessageFactory().createResponse(statusCode, sipRequest);
        response.setStatusCode(statusCode);
        if (msg != null) {
            response.setReasonPhrase(msg);
        }

        if (sipRequest.getMethod().equals(Request.SUBSCRIBE)) {
            log.error("[参数不全] 2xx的SUBSCRIBE回复，必须设置Expires header");
        }

        // 发送response
        sipSender.transmitRequest(sipRequest.getLocalAddress().getHostAddress(), response);

        return response;
    }

}
